<template>
    <div class="filter">
        <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                placeholder="请选择所属单位"
                style="width: 155px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <label for="">排班周期：</label>
            <el-date-picker
                style="width: 260px"
                v-model="searchForm.dateTime"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :size="'default'"
                :disabled-date="disabledDate"
            />
        </div>
        <!-- <div class="filter-item">
            <label for="">姓名：</label>
            <el-input
                v-model="searchForm.userRealName"
                placeholder="请输入员工姓名"
                style="width: 155px"
            />
        </div> -->

        <div class="filter-item">
            <label for="">班组：</label>
            <el-select
                v-model="searchForm.teamId"
                class="m-2"
                clearable
                placeholder="请选择班组"
                style="width: 145px"
            >
                <el-option
                    v-for="item in groupList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <el-button type="primary" @click="search">创建</el-button>
        </div>
        <div class="filter-item">
            <el-button type="primary" @click="reset">重置</el-button>
        </div>
    </div>

    <div class="filter">
        <div class="filter-item">
            <el-button type="warning" @click="handleSave()">保存</el-button>
        </div>
        <div class="filter-item">
            <el-button type="success" @click="schedulingRecord()"
                >排班记录</el-button
            >
        </div>
    </div>
    <div
        v-if="tableData.length == 0"
        style="
            width: 100%;
            line-height: 50px;
            text-align: center;
            color: #909399;
            font-size: 14px;
            border: 1px solid #eee;
        "
    >
        暂无数据
    </div>
    <el-table
        v-else
        :data="tableData"
        border
        :header-cell-class-name="handleCellClassName"
    >
        <el-table-column prop="groupName" width="88" label="班组名称">
        </el-table-column>
        <el-table-column prop="userName" width="88" label="员工姓名" />
        <el-table-column
            :label="
                moment(item.planTime).format('MM-DD') +
                '\n' +
                daysOfWeekForday(item.planTime)
            "
            :prop="item.date"
            v-for="(item, index) in tableData[0].dateList"
            v-if="tableData && tableData.length > 0"
            :key="item.id"
            min-width="114"
            align="center"
            border
            stripe
        >
            <template #default="scope">
                <el-select
                    v-model="scope.row[item.date]"
                    class="m-2"
                    multiple
                    placeholder="选择班次"
                    style="min-width: 88px"
                    size="small"
                >
                    <el-option
                        v-for="t in classesShowList"
                        :key="t.value"
                        :label="t.label"
                        :value="t.value"
                    />
                </el-select>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="searchForm.pageNo"
        v-model:page-size="searchForm.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="paginationStyle"
    />
    <el-dialog v-model="recordListVisible" title="排班记录" width="1000">
        <div class="filter">
            <div class="filter-item">
                <label for="">操作时间：</label>
                <el-date-picker
                    style="width: 240px"
                    v-model="recordTime"
                    type="daterange"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :size="'default'"
                    :disabled-date="disabledDate2"
                />
            </div>
            <div class="filter-item">
                <el-button size="default" type="warning" @click="searchRecord()"
                    >查询</el-button
                >
            </div>
        </div>
        <el-table :data="recordList" style="width: 100%">
            <el-table-column prop="depName" label="所属单位" width="80" />
            <el-table-column prop="createTime" label="排班日期" width="190">
                <template #default="scope">
                    {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
                </template>
            </el-table-column>
            <el-table-column prop="comment" label="详情" width="">
                <template #default="scope">
                    <el-button
                        size="small"
                        type="default"
                        plain
                        @click="showdetail(scope.row)"
                        >详情</el-button
                    >
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="操作时间" width="160" />
            <el-table-column
                prop="operationRealname"
                width="100"
                label="操作人"
            />
        </el-table>
        <el-pagination
            v-model:current-page="recordPageNo"
            v-model:page-size="recordPageSize"
            layout="total, prev, pager, next, jumper"
            :total="totalRecord"
            @size-change="handleSizeChangeRecord"
            @current-change="handleCurrentChangeRecord"
            class="paginationStyle"
        />
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="recordListVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="recordDetailListVisible" title="记录详情" width="800">
        <el-table
            :data="recordDetailList"
            border
            :header-cell-class-name="handleCellClassName"
        >
            <el-table-column prop="groupName" width="88" label="班组名称">
            </el-table-column>
            <el-table-column prop="userName" width="88" label="员工姓名" />
            <el-table-column
                :label="
                    moment(item.planTime).format('MM-DD') +
                    '\n' +
                    daysOfWeekForday(item.planTime)
                "
                :prop="item.date"
                v-for="(item, index) in recordDetailList[0].dateList"
                v-if="recordDetailList && recordDetailList.length > 0"
                :key="item.id"
                min-width="60"
                align="center"
                border
                stripe
            >
                <template #default="scope">
                    {{
                        scope.row[item.date]
                            ? transformClasses(scope.row[item.date])
                            : ""
                    }}
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="recordDetailListVisible = false"
                    >取消</el-button
                >
            </div>
        </template>
    </el-dialog>
</template>


<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import moment from "moment";
import { ElMessage, ElMessageBox } from "element-plus";
// api
import schedulingHttp from "@/https/scheduling.js";
import userHttp from "@/https/user.js";
import { Close, Warning } from "@element-plus/icons-vue";

const disabledDate = (time) => {
    // 禁用今天之前的日期
    let maxTime = moment().endOf("month").add(1, "month").valueOf();
    console.log(maxTime);
    return (
        time.getTime() < Date.now() - 24 * 60 * 60 * 1000 ||
        time.getTime() > maxTime
    ); // 8.64e7 毫秒数代表一天
};
const disabledDate2 = (time) => {
    // 禁用今天之后的日期
    let maxTime = moment().valueOf();
    console.log(maxTime);
    return time.getTime() > maxTime; // 8.64e7 毫秒数代表一天
};
let searchForm = reactive({
    depId: "2",
    userRealName: null,
    teamId: null,
    dateTime: [moment(new Date()), moment().endOf("month")],
    pageNo: 1,
    pageSize: 50,
});

const depIdList = ref([
    { label: "全部", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value;

const tableData = ref([]);
const groupList = ref([]);
// 查询班组信息
const getWorkteamsQueryWorkTeams = async () => {
    let params = {
        depId: searchForm.depId,
        planType: "2",
        pageNo: 1,
        pageSize: 10000,
    };
    const res = await schedulingHttp.workteamsQueryWorkTeams(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.teamName;
            item.value = item.id;
        });
        groupList.value = res.data.data.records;
    }
};

const classesShowList = ref([]);
// 查询班次信息
const getWorkClassQueryWorkClassShow = async () => {
    let params = {
        depId: searchForm.depId,
        isDelete: "0",
        pageNo: 1,
        pageSize: 1000,
    };
    const res = await schedulingHttp.workClassQueryWorkClass(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.className;
            item.shortLabel = item.classShortName + "";
            item.value = item.id;
            item.statusTrigger = false;
        });
        classesShowList.value = res.data.data.records;
    }
};
const currentGroup = ref({});
let total = ref(0);
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
};
const dayLenth = ref(0);
// 查询班次信息;
const search = async () => {
    if (searchForm.teamId) {
        tableData.value = [];
        groupList.value.forEach((item) => {
            if (item.id == searchForm.teamId) {
                currentGroup.value = item;
            }
        });
        if (currentGroup.value.teamMembersNames) {
            let membersList = currentGroup.value.teamMembersNames.split(",");
            let membersIdList = currentGroup.value.teamMembersIds.split(",");
            membersList.forEach((item, index) => {
                let itemObj = {
                    dateList: [],
                    groupId: currentGroup.value.id,
                    groupName: currentGroup.value.teamName,
                    userName: item,
                    userId: membersIdList[index],
                };

                let day = getThTime();
                dayLenth.value = day;
                for (let i = 0; i <= day; i++) {
                    let date = moment(searchForm.dateTime[0])
                        .add(i, "day")
                        .format("YYYY-MM-DD");
                    let dateFormat = moment(searchForm.dateTime[0])
                        .add(i, "day")
                        .format("MM-DD");
                    let dateListItem = {};
                    dateListItem["date"] = dateFormat;
                    dateListItem["planTime"] = date;
                    dateListItem["depId"] = currentGroup.value.depId;
                    dateListItem["depName"] = currentGroup.value.depName;
                    dateListItem["teamId"] = currentGroup.value.id;
                    dateListItem["userId"] = membersIdList[index];
                    dateListItem["planClassIds"] = "";
                    dateListItem["planClassNames"] = "";
                    itemObj.dateList.push(dateListItem);
                    itemObj[dateFormat] = "";
                }
                tableData.value.push(itemObj);
            });
        }
        console.log(tableData.value, "tableDatatableDatatableData");
    } else {
        ElMessage({
            message: "请选择班组",
            type: "warning",
        });
    }
};

// 获取当前日期是周几的文本形式
const daysOfWeek = ref(["日", "一", "二", "三", "四", "五", "六"]);
const daysOfWeekForday = (day) => {
    return daysOfWeek.value[moment(day).day()];
};

const handleCellClassName = ({ columnIndex, rowIndex, row, colum }) => {
    if (rowIndex == 0 && columnIndex > 1) {
        console.log(
            row[columnIndex - 1] &&
                (row[columnIndex - 1].label.indexOf("六") > -1 ||
                    row[columnIndex - 1].label.indexOf("日") > -1)
        );
        // return "weekday";
        if (
            row[columnIndex] &&
            (row[columnIndex].label.indexOf("六") > -1 ||
                row[columnIndex].label.indexOf("日") > -1)
        ) {
            return "weekday dayStyle";
        } else {
            return "dayStyle ";
        }
    }
};
const getThTime = () => {
    //获取当前时间
    let m1 = moment(searchForm.dateTime[0]);
    //获取需要对比的时间
    let m2 = moment(searchForm.dateTime[1]);
    //计算相差多少天 day可以是second minute
    let day = m2.diff(m1, "day");
    return day;
};
const reset = () => {
    const localTypeUnit = ref(Storage.localGet("depId"));
    searchForm.depId = localTypeUnit.value;
    searchForm.userRealName = null;
    searchForm.teamId = null;
    searchForm.dateTime = [moment(new Date()), moment().endOf("month")];
    searchForm.pageNo = 1;
    searchForm.pageSize = 10;
    tableData.value = [];
};
const handleSave = async () => {
    if (searchForm.teamId) {
        tableData.value.forEach((item) => {
            item.dateList.forEach((m, n) => {
                console.log(m.date, item[m.date], "handleSave");
                m.planClassIds = item[m.date] ? item[m.date].join(",") : "";
                m.planClassNames = item[m.date]
                    ? transformClasses(item[m.date])
                    : "";
            });
        });
        console.log(tableData, "tabledata", JSON.stringify(tableData.value));
        let params = {
            depId: currentGroup.value.depId,
            depName: currentGroup.value.depName,
            endTime: moment(searchForm.dateTime[1]).format("YYYY-MM-DD"),
            startTime: moment(searchForm.dateTime[0]).format("YYYY-MM-DD"),
            teamId: currentGroup.value.id,
            teamName: currentGroup.value.teamName,
            userWorkPlanPOLists: [],
            flexiblePlans: JSON.stringify(tableData.value),
        };
        tableData.value.forEach((item) => {
            item.dateList.forEach((m) => {
                if (m.planClassIds) {
                    params.userWorkPlanPOLists.push(m);
                }
            });
        });
        console.log(params, "params");
        const res = await schedulingHttp.flexibleUserWorkPlanBatch(params);
        if (res.data.code == 200) {
            console.log(res);
            ElMessage({
                message: "保存成功",
                type: "success",
            });
            reset();
            tableData.value = [];
        } else {
            ElMessage({
                message: "保存失败",
                type: "error",
            });
        }
    } else {
        ElMessage({
            type: "warning",
            message: "请选择班组！",
        });
    }
};
const transformClasses = (list) => {
    let classesNameList = [];
    list.forEach((item) => {
        classesShowList.value.forEach((t) => {
            if (item == t.id) {
                classesNameList.push(t.className);
            }
        });
    });
    return classesNameList.join(",");
};
const transformdepName = (depId) => {
    let depName = "";
    depIdList.value.forEach((item) => {
        if (depId == item.value) {
            depName = item.label;
        }
    });
    return depName;
};
const recordList = ref([]);
const recordTime = ref([moment().add(-7, "day"), moment()]);
const recordListVisible = ref(false);
const schedulingRecord = async () => {
    recordListVisible.value = true;
    let params = {
        endTime: moment(recordTime.value[1]).format("YYYY-MM-DD"),
        startTime: moment(recordTime.value[0]).format("YYYY-MM-DD"),
    };
    const res = await schedulingHttp.queryFlexibleUserWorkPlanHis(params);
    if (res.data.code == 200) {
        console.log(res.data.data.records);
        res.data.data.records.forEach((item) => {});
        recordList.value = res.data.data.records;
    }
};
const searchRecord = async () => {
    let params = {
        endTime: moment(recordTime.value[1]).format("YYYY-MM-DD"),
        startTime: moment(recordTime.value[0]).format("YYYY-MM-DD"),
    };
    const res = await schedulingHttp.queryFlexibleUserWorkPlanHis(params);
    if (res.data.code == 200) {
        console.log(res.data.data.records);
        res.data.data.records.forEach((item) => {});
        recordList.value = res.data.data.records;
    }
};
const recordDetailListVisible = ref(false);
const recordDetailList = ref([]);
const showdetail = (row) => {
    recordDetailListVisible.value = true;
    console.log(row, "row");
    // let text =
    //     '[{"dateList":[{"date":"12-23","planTime":"2024-12-23","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"6","planClassNames":"病假"},{"date":"12-24","planTime":"2024-12-24","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"6,14","planClassNames":"病假,y测试"},{"date":"12-25","planTime":"2024-12-25","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"","planClassNames":""},{"date":"12-26","planTime":"2024-12-26","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"","planClassNames":""},{"date":"12-27","planTime":"2024-12-27","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"","planClassNames":""},{"date":"12-28","planTime":"2024-12-28","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"","planClassNames":""},{"date":"12-29","planTime":"2024-12-29","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"","planClassNames":""},{"date":"12-30","planTime":"2024-12-30","depId":2,"depName":"星沙","teamId":51,"userId":"9","planClassIds":"","planClassNames":""}],"groupId":51,"groupName":"测试","userName":"李四","userId":"9","12-23":[6],"12-24":[6,14],"12-25":"","12-26":"","12-27":"","12-28":"","12-29":"","12-30":""},{"dateList":[{"date":"12-23","planTime":"2024-12-23","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""},{"date":"12-24","planTime":"2024-12-24","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""},{"date":"12-25","planTime":"2024-12-25","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""},{"date":"12-26","planTime":"2024-12-26","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""},{"date":"12-27","planTime":"2024-12-27","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""},{"date":"12-28","planTime":"2024-12-28","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""},{"date":"12-29","planTime":"2024-12-29","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""},{"date":"12-30","planTime":"2024-12-30","depId":2,"depName":"星沙","teamId":51,"userId":"10","planClassIds":"","planClassNames":""}],"groupId":51,"groupName":"测试","userName":"王五","userId":"10","12-23":"","12-24":"","12-25":"","12-26":"","12-27":"","12-28":"","12-29":"","12-30":""},{"dateList":[{"date":"12-23","planTime":"2024-12-23","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""},{"date":"12-24","planTime":"2024-12-24","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""},{"date":"12-25","planTime":"2024-12-25","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""},{"date":"12-26","planTime":"2024-12-26","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""},{"date":"12-27","planTime":"2024-12-27","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""},{"date":"12-28","planTime":"2024-12-28","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""},{"date":"12-29","planTime":"2024-12-29","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""},{"date":"12-30","planTime":"2024-12-30","depId":2,"depName":"星沙","teamId":51,"userId":"12","planClassIds":"","planClassNames":""}],"groupId":51,"groupName":"测试","userName":"测试2","userId":"12","12-23":"","12-24":"","12-25":"","12-26":"","12-27":"","12-28":"","12-29":"","12-30":""}]';
    recordDetailList.value = JSON.parse(row.flexiblePlans);
    // recordDetailList.value = JSON.parse(text);
    // console.log(recordDetailList.value);
};

onMounted(() => {
    getWorkteamsQueryWorkTeams();
    getWorkClassQueryWorkClassShow();
});
</script>
<style scoped lang="less">
/deep/ .el-table__cell.weekday {
    color: rgba(230, 0, 18, 0.4) !important;
}
/deep/ .el-table__cell.dayStyle {
    font-size: 13px;
    line-height: 1.2;
}
</style>